﻿using MobileControlGuru.AutoTask;
using MobileControlGuru.Base;
using MobileControlGuru.Src;
using MobileControlGuru.Tools;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MobileControlGuru
{
    public partial class IPConnectMulti : MobileControlGuru.BaseForm
    {
        /// <summary>
        /// 
        /// </summary>
        public IPConnectMulti()
        {
            InitializeComponent();
        }
        public MobileControlGuru.MainForm main { set; get; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_main"></param>
        public IPConnectMulti(MobileControlGuru.MainForm _main)
        {
            this.main = _main;

            InitializeComponent();
            resources = new ComponentResourceManager(typeof(IPConnectMulti));
            this.port_input.Text = "5555";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_main"></param>
        public IPConnectMulti(MobileControlGuru.MainForm _main,bool isVisiable)
        {
            this.main = _main;

            InitializeComponent();
            resources = new ComponentResourceManager(typeof(IPConnectMulti));
            this.port_input.Text = "5555";
            this.connect_btn.Visible = !isVisiable;
            this.btnCheck.Visible = isVisiable;
        }
        private async void connect_btn_ClickAsync(object sender, EventArgs e)
        {
            try
            {
                string ipaddress = this.ip_input_device.Text;
                string port = this.port_input.Text;
                if (!string.IsNullOrEmpty(ipaddress) && !string.IsNullOrEmpty(port))
                {
                    this.connect_btn.Enabled = false;
                    string[] iparray = ipaddress.Split(',');
                    List<string> ips = new List<string>();
                    List<Task> ts = new List<Task>();
                    foreach (var ip in iparray)
                    {
                        string ip_port = $"{ip}:{port}";
                        Task t = Task.Run(() =>
                        {
                            Console.WriteLine($"{DateTime.Now} {ip}:{port}");
                            ShowLogMsg($"{DateTime.Now} 开始 {ip}:{port}   ");
                            var adbinfo = ADB.Connect($"{ip}:{port}");

                            Console.WriteLine($"  {DateTime.Now} {ip}:{port}  结果 {adbinfo.Message}  ");
                            ShowLogMsg($"  {DateTime.Now} {ip}:{port}  结果 {adbinfo.Message}  ");

                            LogHelper.Warn($"  {DateTime.Now} {ip}:{port}  结果 {adbinfo.Message}  ");
                        });
                        //var adbinfo = ADB.Connect($"{ip}:{port}");
                        this.connect_btn.Text = $"connect {ip}";
                        //Console.WriteLine($"{adbinfo} 正在执行...{DateTime.Now}");
                        ips.Add(ip_port);

                        ts.Add(t);
                    }


                    await Task.WhenAll(ts.ToArray());

                    // 所有任务完成后的后续操作
                    Console.WriteLine($"所有任务已完成。");

                    ShowLogMsg($"所有任务已完成。{ts.Count}");

                    this.connect_btn.Enabled = true;

                }
            }
            catch (Exception ex)
            {
                // 处理异常或记录日志
                Tools.LogHelper.Error(ex.Message);
                MessageBox.Show("发生异常: " + ex.Message);
                throw;
            }
          
             

        }
        private void ShowLogMsg(string msg)
        {
            //// 确保在UI线程上执行
            if (Application.OpenForms.Count > 0)
            {
                Application.OpenForms[0].Invoke((MethodInvoker)delegate
                {
                    LogForm logForm = LogForm.GetInstance();
                    if (!logForm.Visible)
                    {
                        logForm.Show();
                    }
                    logForm.AppendLog($"{DateTime.Now}:{msg}");

                });
            }
            else
            {
                // 如果没有打开的窗体，可以考虑其他处理方式
                Console.WriteLine("No open forms to attach the log window to.");
            }
        }
        private void IPConnectMulti_Load(object sender, EventArgs e)
        {
            this.port_input.Text = "5555";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string ipaddress = this.ip_input_device.Text;
            string port = this.port_input.Text;
            if (!string.IsNullOrEmpty(ipaddress) && !string.IsNullOrEmpty(port))
            {
                string[] iparray = ipaddress.Split(',');
                List<string> ips = new List<string>();

                foreach (var ip in iparray)
                {
                    string ip_port = $"{ip}:{port}";


                    ips.Add(ip_port);


                }


                // 所有任务完成后的后续操作
                Console.WriteLine("所有任务已完成。");


                //// 可以继续执行其他异步或同步代码
                DeviceManager.Instance.UpdateDevices();
                Properties.Settings.Default.Save();

                string[] connected_ips = DeviceManager.Instance.devices.Select(p => p.Name).ToArray();
                // 使用LINQ的Except方法来获取两个数组的差集
                string[] result = ips.Except(connected_ips).ToArray();

                // 弹出框中要显示的文本
                string messageText = String.Join(",", result);
                if (!string.IsNullOrEmpty(messageText))
                {
                    string msg = messageText.Replace(":5555", "");
                    // 显示弹出框
                    DialogResult dig_result = MessageBox.Show(msg, "未连接的设备,点击即可复制", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

                    if (dig_result == DialogResult.OK)
                    {

                        // 将文本复制到剪贴板
                        Clipboard.SetText(msg);
                        MessageBox.Show("文本已复制到剪贴板！", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);


                    }
                }

                this.Close();
            }

        }
    }


}
